package ru.ssau.customerManagement.model.db;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by illabefat on 20.12.14.
 */
public class DatabaseHelper {
    private static final Logger logger = LoggerFactory.getLogger(DatabaseHelper.class);

//    private final String connectionString;
    
    private final DataSource datasource;

    public DatabaseHelper(DataSource datasource)
    {
        this.datasource = datasource;
    }
    public void executeStatement(String query)
    {
        try {
            logger.info("Performing query '{}'", query);
            Connection conn = datasource.getConnection();
            Statement statement = conn.createStatement();

            statement.execute(query);
            statement.close();
            conn.close();
        } catch (SQLException e) {
            String message = String.format("Failed to execute query '%s'", query);
            logger.error(message, e);
            throw new RuntimeException(message, e);
        }
    }

    public <T> T executeSelect(String query, ResultSetParser<T> parser)
    {
        try {
            logger.info("Performing query '{}'", query);
            Connection conn = datasource.getConnection();
            Statement statement = conn.createStatement();

            ResultSet resultSet = statement.executeQuery(query);

            T result = parser.parse(resultSet);
            logger.info("Got query result: {}", result);
            statement.close();
            conn.close();

            return result;
        } catch (SQLException e) {
            String message = String.format("Failed to execute query '%s'", query);
            logger.error(message, e);
            throw new RuntimeException(message, e);
        }
    }
}
